package com.hk.web.controller.financialPlanner;

import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.sys.SysUserRes;
import com.hk.app.utils.SendMsgCilent;
import com.hk.base.ResponseBase;
import com.hk.commons.CacheConstants;
import com.hk.commons.HqlFilter;
import com.hk.commons.RedisCilent;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Answer;
import com.hk.commons.entity.sys.SysUser;
import com.hk.res.UserRes;
import com.hk.service.sys.IAnswer;
import com.hk.service.sys.ISysUser;

@Controller
@RequestMapping(value = "/finalcial/finalcialCtr")
public class FinancialPlannerLoginCtr {
	private Logger logger = LoggerFactory
			.getLogger(FinancialPlannerLoginCtr.class);

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private SendMsgCilent sendMsgCilent;

	@Autowired
	private IAnswer answerService;

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ResponseBase<SysUserRes> login(@RequestBody UserRes req) {

		logger.info("userName:{} , msgCode:{}", req.getName(), req.getMsgCode());
		ResponseBase<SysUserRes> rb = new ResponseBase<>();
		HqlFilter hqlFilter = new HqlFilter();
		if (StringUtils.isNotEmpty(req.getName())) {
			String msgCode = RedisCilent
					.getString(CacheConstants.FINALCIAL_MOBLIE_MSG_CODE
							+ req.getName());
			String company = RedisCilent
					.getString(CacheConstants.FINALCIAL_MOBLIE_MSG_CODE
							+ req.getName() + "company");
			hqlFilter.addEQFilter("name", req.getName().trim());
			hqlFilter.addEQFilter("closeAccount",0); //只有末销户的用户才能登录-2.7.6
			List<SysUser> list = sysUserService.findByFilter(hqlFilter);
			if (list.size() == 0) {
				rb.setMsg("此用户不存在");
				rb.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
				return rb;
			}

			SysUser loginUser = list.get(0);
			Boolean validateFinancial = sysUserService.isFinUserById(loginUser
					.getId());
			if (validateFinancial) {
				String token = RandomStringUtils.randomAlphanumeric(64);
				SysUserRes sresp = new SysUserRes();
				ReqToModelHelper.copyReqValueToModel(loginUser, sresp);
				sresp.setToken(token);
				RedisCilent.setString(CacheConstants.FINALCIAL_LOG_TOKEN
						+ loginUser.getId(), token, 604800);
				switch (req.getLoginType()) {
				case 1:// 验证码登陆
					if (StringUtils.isNotEmpty(req.getMsgCode())) {
						if (("YIJIA".equals(company) && (StringUtils
								.equalsIgnoreCase(msgCode, req.getMsgCode())))
								|| ("JIGUANG".equals(company) && (validateJG(
										req.getMsgCode(), req.getName(), 0)))) {
							updateMobileType(loginUser, req);
							if (loginUser.getMobileType() == null
									|| (loginUser.getMobileType() != null && (loginUser
											.getMobileType() != req
											.getMobileType()))) {
								loginUser.setMobileType(req.getMobileType());
								sysUserService.update(loginUser);
							}
							if (StringHelper.isEmpty(loginUser.getMobileId())
									|| (!loginUser.getMobileId().equals(
											req.getMobileId()))) {
								if (StringHelper.isNotEmpty(loginUser
										.getMobileId())) {
									Answer an = answerService
											.getByMobileId(loginUser
													.getMobileId());
									if (an != null) {
										an.setMobileId(req.getMobileId());
										answerService.update(an);
									}
								}
								loginUser.setMobileId(req.getMobileId());
								sysUserService.update(loginUser);
								Answer nowMobileAnswer = answerService
										.getByMobileId(req.getMobileId());
								if (nowMobileAnswer != null) {
									answerService.delete(nowMobileAnswer
											.getId());
								}
							}
							sresp.setMobileId(req.getMobileId());
							rb.setResult(sresp);
							RedisCilent
									.delKey(CacheConstants.FINALCIAL_MOBLIE_MSG_CODE
											+ req.getName());
						} else {
							rb.setMsg("验证码不正确，请输入正确的验证码.");
							rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
						}
					} else {
						rb.setMsg("验证码不能为空，请输入正确的验证码.");
						rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
					}
					break;
				case 2:
					if (loginUser.getPwd().equalsIgnoreCase(req.getPwd())) {// 密码登陆如果换手机了，在新手机上第一次都要验证码登陆。更安全，发送到你自己的手机
						// 此时账户和密码相同,再判断UUID 是否相同
						// SysUser loginUser = list.get(0);
						// 如果手机唯一识别码和数据库中用户的唯一识别码相同
						updateMobileType(loginUser, req);
						rb.setResult(sresp);
					} else {
						rb.setMsg("用户名与密码不正确，请输入正确的用户名与密码.");
						rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
					}
					break;
				}
			} else {
				rb.setMsg("该用户不是理财师，不能登陆！");
				rb.setResultCode(ResultCode.NO_RIGHT.getCode());
			}

		} else {
			rb.setMsg("用户名与密码不能为空，请输入正确的用户名与密码.");
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}
		return rb;

	}

	private void updateMobileType(SysUser loginUser, UserRes req) {
		if (loginUser.getMobileType() == null
				|| (loginUser.getMobileType() != null && (loginUser
						.getMobileType() != req.getMobileType()))) {
			loginUser.setMobileType(req.getMobileType());
			sysUserService.update(loginUser);
		}
	}

	private boolean validateJG(String msgCode, String mobile, int status) {
		logger.info("进入极光验证短信");
		Map<String, String> resultJgMap = sendMsgCilent.validate(msgCode,
				mobile, 0);
		logger.info("极光验证mobile={},返回结果={}", mobile,
				new JSONObject(resultJgMap));
		if ("-1111".equals(resultJgMap.get("code"))) {
			return false;
		} else {
			return true;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getMsgCode", method = RequestMethod.GET)
	public ResponseBase<String> getMsgCode(@RequestParam String mobile,
			String ifJG, String channel) {// 1 IOS 2 android
		ResponseBase<String> rb = new ResponseBase<>();
		Random random = new Random();
		String content = "";
		for (int i = 0; i < 6; i++) {
			content += random.nextInt(10);
		}
		Map<String, String> resultMap = sendMsgCilent.senMsgRoute(mobile,
				content, ifJG, channel);
		boolean t = Boolean.valueOf(resultMap.get("result"));
		logger.info("理财师版:after  getMsgCode  mobile: {} , send status:{}",
				mobile, t);
		if (t) {
			String company = resultMap.get("company");
			RedisCilent.setString(CacheConstants.FINALCIAL_MOBLIE_MSG_CODE
					+ mobile + "company", company, 300);
			if ("YIJIA".equals(company)) {
				RedisCilent.setString(CacheConstants.FINALCIAL_MOBLIE_MSG_CODE
						+ mobile, content, 1000);
			}
			rb.setResult(content);
		} else {
			rb.setMsg("短信发送失败");
			rb.setResultCode(ResultCode.FAILED.getCode());
		}
		return rb;
	}

	@ResponseBody
	@RequestMapping(value = "/reSetPwd", method = RequestMethod.POST)
	public ResponseBase<Boolean> reSetPwd(@RequestBody UserRes res) {
		ResponseBase<Boolean> rb = new ResponseBase<>();

		if (StringUtils.isNotEmpty(res.getPwd())) {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("name", res.getName());
			hqlFilter.addEQFilter("closeAccount",0); //只有末销户的用户才能重置密码-2.7.6
			List<SysUser> list = sysUserService.findByFilter(hqlFilter);
			if (list.size() != 0) {
				SysUser user = list.get(0);
				user.setPwd(res.getPwd());
				sysUserService.update(user);
				rb.setResult(true);
			}
		} else {
			rb.setMsg("密码不能为空");
			rb.setResult(false);
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}
		return rb;
	}
}